package com.yj.cmp.sdk.fusioncompute.common.utils;

import com.google.gson.Gson;
import com.yj.cmp.sdk.fusioncompute.common.constants.ResponseConstants;
import com.yj.cmp.sdk.fusioncompute.common.exception.RequestException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author Harvey_Yang
 * @date 2021/8/28 11:44
 */
public class RequestUtils {

    public static synchronized Retrofit getClient(String address) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .sslSocketFactory(SslSocketClient.getSslSocketFactory())
                .hostnameVerifier(SslSocketClient.getHostnameVerifier())
//                .addInterceptor(TestUtils.interceptor())
                .build();

        return new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(address)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

    }


    public static <T> void isSuccessful(Response<T> response) throws Exception {
        if (response.code() != ResponseConstants.CODE_200) {
            if (null == response.errorBody()) {
                throw new RequestException("错误信息为空!");
            } else {
                throw new RequestException(response.errorBody().string());
            }
        }
    }

    public static RequestBody toRequestBody(Object obj) {
        String strEntity = new Gson().toJson(obj);
        return RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), strEntity);
    }

}
